#!/bin/bash

# Configuration parameters
APP_DIR="${APP_DIR:-/data/metro-crawler}"  # Default path that can be overridden
LOG_DIR="${LOG_DIR:-$APP_DIR/logs}"
PID_FILE="$APP_DIR/ocent-crawler.pid"

# Function to check if a process is running
is_process_running() {
    local pid=$1
    if [ -z "$pid" ]; then
        return 1
    fi
    
    # Check if process exists
    if ps -p "$pid" > /dev/null 2>&1; then
        return 0
    else
        return 1
    fi
}

# Function to stop process gracefully
stop_process() {
    local pid=$1
    local process_name=$2
    
    if is_process_running "$pid"; then
        echo "Stopping $process_name (PID: $pid)..."
        
        # Try graceful shutdown first (SIGTERM)
        kill "$pid" 2>/dev/null
        
        # Wait up to 10 seconds for graceful shutdown
        local count=0
        while [ $count -lt 10 ]; do
            if ! is_process_running "$pid"; then
                echo "$process_name stopped gracefully"
                return 0
            fi
            sleep 1
            count=$((count + 1))
        done
        
        # Force kill if still running (SIGKILL)
        echo "Force stopping $process_name..."
        kill -9 "$pid" 2>/dev/null
        
        # Wait a bit more
        sleep 2
        if ! is_process_running "$pid"; then
            echo "$process_name force stopped"
            return 0
        else
            echo "Warning: Failed to stop $process_name"
            return 1
        fi
    else
        echo "$process_name is not running"
        return 0
    fi
}

# Main stop logic
echo "Stopping Ocent Crawler..."

# Check if PID file exists
if [ ! -f "$PID_FILE" ]; then
    echo "PID file not found at: $PID_FILE"
    echo "The crawler may not be running or was started manually"
    exit 1
fi

# Read the main process PID
MAIN_PID=$(cat "$PID_FILE" 2>/dev/null)

if [ -z "$MAIN_PID" ]; then
    echo "Error: Could not read PID from file $PID_FILE"
    exit 1
fi

echo "Found main process PID: $MAIN_PID"

# Stop the main Node.js process
if stop_process "$MAIN_PID" "Ocent Crawler"; then
    # Remove PID file after successful stop
    rm -f "$PID_FILE"
    echo "PID file removed"
else
    echo "Warning: Main process may still be running"
fi

# Find and stop any related log rotation processes
echo "Checking for log rotation processes..."
LOG_ROTATE_PIDS=$(ps aux | grep "check_and_rotate_log" | grep -v grep | awk '{print $2}')

if [ -n "$LOG_ROTATE_PIDS" ]; then
    for pid in $LOG_ROTATE_PIDS; do
        stop_process "$pid" "Log rotation process"
    done
else
    echo "No log rotation processes found"
fi

# Find and stop any remaining related processes
echo "Checking for any remaining ocent-crawler processes..."
REMAINING_PIDS=$(ps aux | grep -E "(node.*index\.js|ocent-crawler)" | grep -v grep | grep -v "$0" | awk '{print $2}')

if [ -n "$REMAINING_PIDS" ]; then
    echo "Found remaining processes:"
    for pid in $REMAINING_PIDS; do
        ps -p "$pid" -o pid,ppid,cmd | grep -v PID
        stop_process "$pid" "Related process"
    done
else
    echo "No remaining processes found"
fi

# Final status check
echo ""
echo "=== Final Status ==="
if [ -f "$PID_FILE" ]; then
    echo "Warning: PID file still exists: $PID_FILE"
else
    echo "✓ PID file cleaned up"
fi

# Check for any remaining processes
FINAL_CHECK=$(ps aux | grep -E "(node.*index\.js|ocent-crawler)" | grep -v grep | grep -v "$0")
if [ -n "$FINAL_CHECK" ]; then
    echo "Warning: Some processes may still be running:"
    echo "$FINAL_CHECK"
else
    echo "✓ All processes stopped successfully"
fi

echo ""
echo "Ocent Crawler shutdown complete"
echo "Log files are preserved in: $LOG_DIR" 